<template>
  <div class="report-container">
    <van-nav-bar title="报告单列表" left-text="返回" left-arrow @click-left="back">
      <template #right>
        <van-icon name="ellipsis" size="18" @click="showShare = true"/>
		<van-share-sheet
		  v-model:show="showShare"
		  title="立即分享给好友"
		  :options="shareOptions"
		  @select="onShareSelect"
		/>
      </template>
    </van-nav-bar>
	<!-- 就诊人切换 -->
	 <div class="filter-area">
	    <van-cell
	      :title="currentPatient.name"
	    />
	  </div>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div
          v-for="item in reports"
          :key="item.report_id"
          class="report-card"
          @click="showReportDetails(item)"
        >
          <div class="report-header">
            <span class="report-type">{{ item.type }}报告</span>
            <span class="report-time">{{ formatDate(item.report_time) }}</span>
          </div>
          <div class="report-content">
            <h3>{{ item.name }}</h3>
            <p class="report-desc">{{ item.content }}</p>
          </div>
          <div class="report-footer">
            <van-tag plain type="primary">检查时间: {{ formatDate(item.check_time) }}</van-tag>
            <van-icon name="arrow" />
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <van-popup v-model:show="showDetail" position="bottom" round style="height:80%">
      <div class="report-detail">
        <div class="detail-header">
          <h2>{{ currentReport.name }}</h2>
          <van-icon name="cross" @click="showDetail = false" />
        </div>
        <div class="detail-meta">
          <van-tag type="primary">{{ currentReport.type }}报告</van-tag>
          <span>报告时间: {{ formatDate(currentReport.report_time) }}</span>
        </div>
        <div class="detail-content">
          <h3>检查结果</h3>
          <p>{{ currentReport.content }}</p>
          <h3>报告图片</h3>
          <van-image v-if="currentReport.report_url" :src="currentReport.report_url" height="200" fit="contain"/>
          <p v-else>暂无报告图片</p>
        </div>
      </div>
    </van-popup>

  </div>
</template>

<script setup>
import { ref, onMounted,computed,watch } from 'vue'
import { useRouter } from 'vue-router'
import { showFailToast } from 'vant'
import axios from 'axios'
import { useUserStore } from '../stores/user.js';

// 获取 store 实例
const userStore = useUserStore();

// 定义当前就诊人变量，初始值从 store 中获取
const currentPatient = ref(userStore.defaultPatient || { name: '未设置默认就诊人' });

const onShareSelect = ()=>{
	console.log("分享")
}

const router = useRouter()
//分享面板
const showShare = ref(false);
//从浏览器记录获取当前登录用户信息
const userId = localStorage.getItem('userId')
const currentUserName = localStorage.getItem('username')

const showPatientList = ref(false)

const reports = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)

const showDetail = ref(false)
const currentReport = ref({})

const formatDate = (d) => (d ? new Date(d).toLocaleString() : '-')
const back = () => router.go(-1)

// 分享选项
const shareOptions = ref([
  { name: '微信', icon: 'wechat' },
  { name: '朋友圈', icon: 'wechat-moments' },
  { name: '微博', icon: 'weibo' },
  { name: 'QQ', icon: 'qq' },
]);


const fetchReports = async () => {
  if (!userId) return
  // 检查当前就诊人是否存在有效ID
  if (!currentPatient.value || !currentPatient.value.patient_id) {
    showFailToast('请选择就诊人');
    loading.value = false;
    return;
  }
  loading.value = true
  try {
    const params = {
      // 动态使用当前就诊人的ID
      patientId: currentPatient.value.patient_id, 
      username: currentUserName,
      ...(currentPatient.value.patient_id !== -1 && { patientName: currentPatient.value.name })
    }
    const { data } = await axios.get('/api/v1/report', { params })
    reports.value = data.code === 0 ? data.data : []
  } catch (e) {
    console.error(e)
    showFailToast('获取报告失败')
  } finally {
    loading.value = false
    finished.value = true
    refreshing.value = false
  }
}


watch(
  () => userStore.defaultPatient,
  (newVal) => {
    if (newVal) {
      currentPatient.value = newVal
      fetchReports() // 重新获取报告
    }
  },
  { immediate: true }
)

const onLoad = () => fetchReports()
const onRefresh = () => {
  refreshing.value = true
  finished.value = false
  fetchReports()
}

const showReportDetails = (item) => {
  currentReport.value = item
  showDetail.value = true
}

onMounted(() => {
  fetchReports()
})
</script>


<style scoped>
.report-container {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.filter-area {
  background-color: #fff;
  margin-bottom: 10px;
}

.report-list {
  padding: 10px;
}

.report-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.report-type {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  color: #fff;
}

.type-lab {
  background-color: #1989fa;
}

.type-exam {
  background-color: #07c160;
}

.type-micro {
  background-color: #ff976a;
}

.report-time {
  font-size: 12px;
  color: #969799;
}

.report-content h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #323233;
}

.report-desc {
  font-size: 13px;
  color: #646566;
  margin: 0;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.report-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f5f5f5;
}

.report-footer :deep(.van-tag) {
  font-size: 11px;
}

.report-detail {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-header h2 {
  margin: 0;
  font-size: 18px;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  font-size: 13px;
  color: #969799;
}

.detail-content h3 {
  font-size: 16px;
  margin: 20px 0 10px 0;
  color: #323233;
}

.detail-content p {
  font-size: 14px;
  color: #646566;
  line-height: 1.6;
  margin-bottom: 20px;
}

.report-images {
  margin: 15px 0;
}

:deep(.van-swipe) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.van-image) {
  background-color: #f5f5f5;
}

.patient-list {
  padding: 20px;
  
  h3 {
    text-align: center;
    margin-bottom: 15px;
  }
}
</style>